import { Component, OnInit, Inject } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { recodeModule} from '../../../service/delivent/recodeModule';
import {UtilityService} from '../../../service/utils.service';
import {appConfig} from '../../../service/common';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import * as moment from 'moment';
import * as _ from 'lodash';

@Component({
    selector: 'app-delay',
    templateUrl: './delay.component.html',
     styleUrls: ['./delay.component.less'],
})
export class DelayComponent implements OnInit {
    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
          private confirmServ: NzModalService,
       @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    ) { }
   role:any;
     ngOnInit() {
        this.role = this.tokenService.get().role;
        this.getData();

  }
    data:any[]=[]
    listloading = false;
    showAdd = true;
    isPagination = true;
    expandForm  = false;
    headerDate = [  // 配置表头内容
        { label: '工作项', value: 'itemName', isclick: false },
        { label: '操作人', value: 'applyPerson', isclick: false },
        { label: '状态', value: 'repealStatus', isclick: false },
        { label: '环境', value: 'profilesName', isclick: false },    
        { label: '撤销时间', value: 'repealTime', isclick: false },
        { label: '撤销理由', value: 'repealDesc', isclick: false },
			
    ];
 pageIndex = 1;
 total:number;
 pageTotal:number;
 search ={
     repealStatus:null,
     itemName:null,
     profilesName:null
 }
 repealStatus = [
       {label:'已延期',value:"0"},
     {label:'延期中',value:"1"},
 ]
  getData(option?) {
        if (option) {
           this.pageIndex =1;
        }
        
          
        let page = {

                condition: this.search, // 搜索内容
                page: {
                    current: this.pageIndex,
                    size: 10,
                    orderByField: 'guid',
                    asc: false // asc 默认是true  升序排序，时间类型 用false， 降序
                }
            };
       this.listloading = true;
        this.utilityService.postData(appConfig.testUrl  + '/sRepeal/all', page )
            .subscribe(
                (val) => {
                       this.listloading = false;
                    
                        this.total = val.result.total; // 总数
                        this.pageTotal = val.result.pages * 10; // 页码
                            val.result.records.forEach(element => {
                                if(this.role==="RCT小组"){
                        if(element.repealStatus !== "已延期"){
                                  element.buttonData= [
                                        {key: 'dels', value: '删除' },
                                        {key: 'rollback', value: '确认延期'},
                                        {key: 'detail', value: '详细'}
                                    ]
                                }else{
                                          element.buttonData= [                                       
                                        {key: 'again', value: '再次投放'},     
                                        {key: 'detail', value: '详细'},                               
                                    ]
                                }

                                }else{
                                    if(element.repealStatus !== "已延期"){
                                  element.buttonData= [
                                        {key: 'dels', value: '删除' },
                                        {key: 'detail', value: '详细'}
                                    ]
                                }else{
                                          element.buttonData= [                                       
                                        {key: 'again', value: '再次投放'},     
                                        {key: 'detail', value: '详细'},                               
                                    ]
                                }
                                }
                       element.repealTime = moment(element.repealTime ).format('YYYY-MM-DD HH:mm:ss');
                       
                 });
                this.data = val.result.records;
                   
                  console.log(val)
                },(error)=>{
                        this.listloading = false;
                this.nznot.create('error', error.code , error.msg);
                })
    }
 checkModalData = []

  delaysModal = false;
  id:number;
    buttonEvent(it){
        this.id = it.guid;
         let self = this;
        switch(it.names.key){
            case 'dels':
        
            this.confirmServ.confirm({
                title  : '提示',
                content:'<b>您是否确认要删除此项撤销申请!</b>',
                showConfirmLoading: true,
                onOk() {
                    self.utilityService.deleatData(appConfig.testUrl  + '/sRepeal/' + it.guid)
                        .subscribe(
                            (val) => {
                                if (val.code === '200') {
                                    if ( !(( self.total - 1) % 10)) {
                                        self.pageTotal = self.pageTotal - 10 ;
                                    }
                                    self.getData();
                                    self.nznot.create('success', val.msg, val.msg);
                                }else {
                                    self.nznot.create('error', val.msg, '');
                                }
                            }   ,
                            (error) => {
                                self.nznot.create('error', error.msg, '');

                            }
                        );
                },
                onCancel() {
                }
            });
            break;
            case 'again':
            this.getdelay()
            break;
            case 'detail':
             this.listloading = true;
            
            this.utilityService.getData(appConfig.testUrl  + '/sRepeal/'+this.id+'/repealListDetail')
               .subscribe(
                (val) => {
                    
                  this.checkModalData = val.result;
                  this.listloading = false;
                  this.delaysModal = true;
                },(error)=>{
                  this.listloading = false;
                  this.nznot.create('error', error.code , error.msg);
                })
            break;
          case 'rollback':
          
            this.confirmServ.confirm({
                title  : '提示',
                content:'<b>您是否确认此项延期申请!</b>',
                showConfirmLoading: true,
                onOk() {
                    self.utilityService.putData(appConfig.testUrl  + '/sRepeal/'+it.guid)
                        .subscribe(
                            (val) => {
                                if (val.code === '200') {
                                
                                    self.getData();

                                    self.nznot.create('success', val.msg, val.msg);
                                }else {
                                    self.nznot.create('error', val.code,val.msg);
                                }
                            }   ,
                            (error) => {
                                self.nznot.create('error', error.code,error.msg);

                            }
                        );
                },
                onCancel() {
                }
            });
            break;

        }
         
    }
 monitorHandler(event){

 }
delayPageIndex = 1;
searchRevert:string;
delayListData = [];
delaypageTotal:number;
delayListModal = false;
    loading = false;
    isdelayPagination = true;
    delayHeaderDate = [
        { label: '序号', value: 'index', isclick: false },
        { label: '代码', value: 'fullPath', isclick: false }
    ]
       isCaocuo = false;
  getdelay(option?){
          if (option) {
           this.delayPageIndex =1;
        }
        const page = {
                    condition: {fullPath:this.searchRevert}, // 搜索内容
                        page: {
                            size: 10,
                            current: this.delayPageIndex
                        }
                    };
                      this.listloading = true;
                      
            this.utilityService.postData(appConfig.testUrl  +'/sRepeal/'+this.id+'/repealListDetail', page )
                .subscribe(
                    (val) => {
                                  this.listloading = false;
                                  val.result.records.forEach((i,index)=>{
                                      val.result.records[index]['index'] = index+1;
                                      i.checked = false;
                                  });
                                   this.delayListData = val.result.records
                                  this.delaypageTotal = val.result.pages * 10;  
                                  this.delayListModal = true
                    },(error)=>{
                           this.delayListModal = false;
                          this.nznot.create('error', error.code,error.msg);
                    })
         }
           getdelays = []
    selectedRow(event) {
          this.getdelays = []
          event.selectedRows.forEach(i=>{
              this.getdelays.push(i.guid)
        })
    }
       onSearch(it){
         this.searchRevert = it;
         this.getdelay(it)
     } 
     updPackTiming = [];
     updEnvironment = false;
     packTime:any;
     getGodelayList(){
           if(this.getdelays.length == 0){
              this.nznot.create('error','请勾选代码' ,'');
              return
          }
           this.loading = true;
           this.utilityService.getData(appConfig.testUrl  +'/sRepeal/'+this.id+'/packTimeVerify')
                .subscribe(
                    (val) => {
                        console.log(val)
                         this.loading = false;
                    this.updPackTiming  = val.result
                            this.updPackTiming['unixTime'] = moment(this.updPackTiming['deliveryTime']).format('YYYY-MM-DD 00:00:00.000')
                       
                            for (let i = 0; i < this.updPackTiming['packTimeDetails'].length; i++) {
                                if (this.updPackTiming['packTimeDetails'][i]['isOptions'] === 'D'){
                                    this.updPackTiming['packTiming']   =   this.updPackTiming['packTimeDetails'][i]['packTime']
                                }
                            }
                            this.updPackTiming['deliveryTime'] = new Date(this.updPackTiming['deliveryTime']);
                            this.updEnvironment = true;
                            this.packTime = this.updPackTiming['packTiming']
                    },(error)=>{
                       this.loading = false;
                          this.nznot.create('error', error.code,error.msg);
                    })
     }
    _disabledDate(current: Date): boolean {
        let time = localStorage.getItem('time');
        return current && current.getTime() < new Date(time).getTime();
    }

    onChange(updPackTiming) {

        if (updPackTiming.deliveryTime.getTime() !== new Date(updPackTiming.unixTime).getTime()) {
          
            for (let i = 0; i < this.updPackTiming['packTimeDetails'].length; i++) {
          
                if (this.updPackTiming['packTimeDetails'][i]['isOptions'] === 'N') {
                    this.updPackTiming['packTimeDetails'][i]['isOptions']  = 'No';
                    
                }
            }
        } else {
              this.updPackTiming['packTiming']=this.packTime
            for (let i = 0; i < this.updPackTiming['packTimeDetails'].length; i++) {
                if (this.updPackTiming['packTimeDetails'][i]['isOptions']  === 'No') {
                    this.updPackTiming['packTimeDetails'][i]['isOptions']  = 'N';
                }
            }

        }
      

    }
   
   reset(){
        this.search ={
     repealStatus:null,
     itemName:null,
     profilesName:null
 }
 this.getData();
   }
     submitUpd(){
            let obj =
            {
              deliveryTime: moment(this.updPackTiming['deliveryTime'].getTime()).format('YYYY-MM-DD'),
              guidRepeal: this.id,
              guidRepealLists: this.getdelays,
              packTiming: this.updPackTiming['packTiming']
                }
            this.loading = true;
             this.utilityService.postData(appConfig.testUrl  + '/sRepeal/againDelivery', obj )
            .subscribe(
                (val) => {
                      this.loading = false;
                        this.updEnvironment = false;
                          this.delayListModal = false
                          this.getData();
                      this.nznot.create('success', val.code,val.msg);
                      },(error)=>{
                       this.loading = false;
                       this.nznot.create('error', error.code,error.msg);
                    })
     }
}